const model = require('../models/models');
const User = model.user;
User.findOne({
  mobile: req.body.mobile
}, (err, user) => {
  if(err){
    throw err;
  }
  if(user){
    res.json({
      errorCode: 2,
      message: '用户已经注册!'
    });
  } else {
    var token = jwt.sign({
      mobile: phoneNum + Date.now(),
    }, config.secret, {});
    var newUser = new User({
      countryCode: countryCode,
      mobile: mobile,
      password: req.body.password,
      token: token,
      isEnabled: true,
      roleType: 0
    });
    newUser.userCode = newUser._id;
    //send 4 digits code.
    var randCode = Math.floor(1000 + Math.random() * 9000);
    console.debug('sms random code=%s', randCode);
    var msg = '【秀】您的验证码是' + randCode + '。如非本人操作，请忽略。请在60分钟之内完成验证操作';
    sms.sendsms(phoneNum, msg, function(data) {
    });
    //setup the session for 2FA
    var s = {
      timestamp: Date.now() + 180000,
      user: newUser,
      verifyCode: randCode
    };
    var md5str = md5(token);
    console.log(md5str);
    console.log(md5(token));
    sess[md5str] = s;
    res.json({
      errorCode: 1,
      message: '4 digits code sent!',
      data: {
        token: token,
        userCode: newUser._id
      }
    })
  }
})

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://dbadmin:ESPL888espl@espldb-wwcqu.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  console.log(collection);
  client.close();
});
